package com.atguigu.flink.chapter06.state.keyed;


import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.function.WaterSensorMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/*
键控状态:
    状态生存时间（TTL）
 */
public class StateTTLDemo {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        //输出每个传感器的最大水位
        env.socketTextStream("hadoop102",8888)
                .map(new WaterSensorMapFunction())
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    private ValueState<Integer> maxVcState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<Integer> desc = new ValueStateDescriptor<>("maxVc", Integer.class);
                        //给状态设置ttl
                        StateTtlConfig ttlConf = StateTtlConfig.newBuilder(Time.seconds(30))   //状态存活30s
                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite) //设置状态的更新策略
                                //.updateTtlOnCreateAndWrite()
                                .setStateVisibility(StateTtlConfig.StateVisibility.ReturnExpiredIfNotCleanedUp) //状态的可见性
                                //.setTtlTimeCharacteristic()    //ttl的时间语义：目前只支持处理时间
                                //.neverReturnExpired()
                                .build();

                        desc.enableTimeToLive(ttlConf);
                        //在open方法中获取需要的键控状态
                        maxVcState = getRuntimeContext().getState(desc);
                    }

                    @Override
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {
                        if (maxVcState.value() == null){
                            maxVcState.update(value.getVc());
                        }else {
                            System.out.println(maxVcState.value());
                        }
                    }
                })
                .print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



//public class StateTTLDemo {
//    public static void main(String[] args) {
//        Configuration conf = new Configuration();
//        conf.setInteger("rest.port",2000);
//        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
//        env.setParallelism(1);
//        //输出每个传感器的最大水位
//        env.socketTextStream("hadoop102",8888)
//                .map(new WaterSensorMapFunction())
//                .keyBy(WaterSensor::getId)
//                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
//
//                    private ValueState<Integer> maxVcState;
//
//                    @Override
//                    public void open(Configuration parameters) throws Exception {
//                        ValueStateDescriptor<Integer> desc = new ValueStateDescriptor<>("maxVc", Integer.class);
//                        //给状态设置ttl
//                        StateTtlConfig ttlConfig = StateTtlConfig.newBuilder(Time.seconds(30))   //状态存活30s
//                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)    //设置状态的更新策略
//                                .setStateVisibility(StateTtlConfig.StateVisibility.ReturnExpiredIfNotCleanedUp)   //设置状态的可见性
//                                .build();
//
//                        desc.enableTimeToLive(ttlConfig);
//                        //在open方法中获取需要的键控状态
//                        maxVcState = getRuntimeContext().getState(desc);
//                    }
//
//                    @Override
//                    public void processElement(WaterSensor value,
//                                               Context ctx,
//                                               Collector<String> out) throws Exception {
//                        if (maxVcState.value() == null){
//                            maxVcState.update(value.getVc());
//                        }else {
//                            System.out.println(maxVcState.value());
//                        }
//                    }
//                })
//                .print();
//        try {
//            env.execute();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//}


//public class StateTTLDemo {
//    public static void main(String[] args) {
//        Configuration conf = new Configuration();
//        conf.setInteger("rest.port",2000);
//        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
//        env.setParallelism(1);
//        //输出每个传感器的最大水位
//        env.socketTextStream("hadoop102",8888)
//                .map(new WaterSensorMapFunction())
//                .keyBy(WaterSensor::getId)
//                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
//
//                    private ValueState<Integer> maxVcState;
//
//                    @Override
//                    public void open(Configuration parameters) throws Exception {
//                        ValueStateDescriptor<Integer> desc = new ValueStateDescriptor<>("maxVc", Integer.class);
//                        //给状态设置ttl
//                        StateTtlConfig ttlConfig = StateTtlConfig.newBuilder(Time.seconds(30))  //状态存活30s
//                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)       //设置状态的更新策略
//                                .setStateVisibility(StateTtlConfig.StateVisibility.ReturnExpiredIfNotCleanedUp)  //设置状态的可见性
//                                .build();
//                        desc.enableTimeToLive(ttlConfig);
//                        //在open方法中获取需要的键控状态
//                        maxVcState = getRuntimeContext().getState(desc);
//                    }
//
//                    @Override
//                    public void processElement(WaterSensor value,
//                                               Context ctx,
//                                               Collector<String> out) throws Exception {
//                        if (maxVcState.value() == null){
//                            maxVcState.update(value.getVc());
//                        }else {
//                            System.out.println(maxVcState.value());
//                        }
//                    }
//                })
//                .print();
//
//
//        try {
//            env.execute();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//}



//public class StateTTLDemo {
//    public static void main(String[] args) {
//        Configuration conf = new Configuration();
//        conf.setInteger("rest.port",2000);
//        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
//        env.setParallelism(1);
//        //输出每个传感器的最大水位
//        env.socketTextStream("hadoop102",8888)
//                .map(new WaterSensorMapFunction())
//                .keyBy(WaterSensor::getId)
//                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
//
//                    private ValueState<Integer> maxVcState;
//
//                    @Override
//                    public void open(Configuration parameters) throws Exception {
//                        ValueStateDescriptor<Integer> desc = new ValueStateDescriptor<>("maxVc", Integer.class);
//                        //给状态设置ttl
//                        StateTtlConfig ttlConfig = StateTtlConfig.newBuilder(Time.seconds(30))  //设置状态存活时间为30s
//                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)    //设置状态的更新策略
//                                .setStateVisibility(StateTtlConfig.StateVisibility.ReturnExpiredIfNotCleanedUp) //设置状态的可见性
//                                .build();
//
//                        desc.enableTimeToLive(ttlConfig);
//                        //在open方法中和获取需要的键控状态
//                        maxVcState = getRuntimeContext().getState(desc);
//                    }
//
//                    @Override
//                    public void processElement(WaterSensor value,
//                                               Context ctx,
//                                               Collector<String> out) throws Exception {
//                        if (maxVcState.value() == null){
//                            maxVcState.update(value.getVc());
//                        }else {
//                            System.out.println(maxVcState.value());
//                        }
//                    }
//                })
//                .print();
//        try {
//            env.execute();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//}



//public class StateTTLDemo {
//    public static void main(String[] args) {
//        Configuration conf = new Configuration();
//        conf.setInteger("rest.port",2000);
//        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
//        env.setParallelism(1);
//        //输出每个传感器的最大水位
//        env.socketTextStream("hadoop102",8888)
//                .map(new WaterSensorMapFunction())
//                .keyBy(WaterSensor::getId)
//                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
//
//                    private ValueState<Integer> maxVcState;
//
//                    @Override
//                    public void open(Configuration parameters) throws Exception {
//                        ValueStateDescriptor<Integer> desc = new ValueStateDescriptor<>("maxVc", Integer.class);
//
//                        //给状态设置ttl
//                        StateTtlConfig ttlConfig = StateTtlConfig.newBuilder(Time.seconds(30))   //设置状态存活时间30s
//                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)  //设置状态的更新策略
//                                .setStateVisibility(StateTtlConfig.StateVisibility.ReturnExpiredIfNotCleanedUp)   //设置状态的可见性
//                                .build();
//
//                        desc.enableTimeToLive(ttlConfig);
//
//                        //在open方法中获取需要的键控状态
//                        maxVcState = getRuntimeContext().getState(desc);
//                    }
//
//                    @Override
//                    public void processElement(WaterSensor value,
//                                               Context ctx,
//                                               Collector<String> out) throws Exception {
//                        if (maxVcState.value() == null){
//                            maxVcState.update(value.getVc());
//                        }else {
//                            System.out.println(maxVcState.value());
//                        }
//                    }
//                })
//                .print();
//
//
//        try {
//            env.execute();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//}